package com.tensquare.user.web.interceptor;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import utils.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("经过了JwtInterceptor拦截器。。。");
        String jwtAuthorization = request.getHeader("JwtAuthorization");
        if(null!=jwtAuthorization && jwtAuthorization.startsWith("Bearer ")){
            String token = jwtAuthorization.substring(7);
            Claims claims = null;
            try{
                claims = jwtUtil.parseJWT(token);
            }catch (Exception e){
                e.printStackTrace();
            }

            if(null!=claims){
                if("admin".equals(claims.get("roles"))){
                    request.setAttribute("admin_claims",claims);
                }
                if("user".equals(claims.get("roles"))){
                    request.setAttribute("user_claims",claims);
                }
            }
        }
        return true;
    }
}
